package com.ifonly.render.renders;

import com.google.common.base.Strings;
import com.ifonly.common.ContentTypeMapping;
import com.ifonly.render.Render;
import com.ifonly.render.RenderException;
import com.ifonly.render.RenderFactory;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author <a href="mailto:ifonlymaster@163.com">ifonly</a>
 * @version 1.0 2015-12-10 15:03
 * @since JDK 1.6
 */
public class ErrorRender extends Render {

    private String default_error_html = "<html><head><title>error</title></head><body><h2 style='text-align: center;'>系统出错了!!!<h2></body></html>";

    private static Map<Integer, String> ERROR_CODE_HTML_MAPPING = new HashMap<Integer, String>() {
        private static final long serialVersionUID = 4707582162783579723L;

        {
            put(404, "<html><head><title>404</title></head><body><h2 style='text-align: center;'>404<h2></body></html>");
            put(500, "<html><head><title>500</title></head><body><h2 style='text-align: center;'>500<h2></body></html>");


            put(10001, "<html><head><title>禁止访问</title></head><body><h2 style='text-align: center;'>禁止访问<h2></body></html>");
        }
    };

    private int errorCode;
    private String view;

    public ErrorRender(int errorCode, String view) {
        this.errorCode = errorCode;
        this.view = view;
    }


    @Override
    public void render() {
        if (!Strings.isNullOrEmpty(this.view)) {
            RenderFactory.getRender(this.view).init(request, response).render();
            return;
        }

        String html = ERROR_CODE_HTML_MAPPING.get(errorCode);
        if (Strings.isNullOrEmpty(html)) {
            html = default_error_html;
        }
        PrintWriter out = null;
        try {
            response.setContentType(ContentTypeMapping.TEXT_HTML.contentType);
            out = response.getWriter();
            out.println(html);
            out.flush();
        } catch (IOException e) {
            throw new RenderException(e);
        } finally {
            if (out != null) {
                out.close();
            }
        }

    }
}
